package com.hulk.dryad.web.oauth2.basic.component;


import com.hulk.dryad.manage.security.component.PermitAllSecurityUrlProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;

/**
 * 改造 {@link BearerTokenExtractor} 对公开权限的请求不进行校验
 *
 * @author hulk
 * @date 2020.05.15
 */
@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(PermitAllSecurityUrlProperties.class)
public class DryadBearerTokenExtractor extends BearerTokenExtractor {

	private final PathMatcher pathMatcher = new AntPathMatcher();

	private final PermitAllSecurityUrlProperties permitAllSecurityUrlProperties;

	@Override
	public Authentication extract(HttpServletRequest request) {
		boolean match = permitAllSecurityUrlProperties.getPermitAll().stream()
				.anyMatch(url -> pathMatcher.match(url, request.getRequestURI()));

		return match ? null : super.extract(request);
	}

}
